#include <pthread.h>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <fcntl.h>
#include <functional>
#include <unistd.h>
#include <mutex>
#include <cstring>
#include "BlockQueue.hpp"
#include "Thread.hpp"

using namespace std;
using namespace zzz;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pro_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t con_cond = PTHREAD_COND_INITIALIZER;

void productFunc(BlockQueue<int> &q, string &name) // 生产线程函数——去放数据
{
    static int data = 1;
    while (1)
    {
        q.Enqueue(data, name);
        cout << "生产者外部>> " << name << "放上数据了:" << data++ << endl;
        sleep(1);
    }
}
void create_product(vector<Thread<BlockQueue<int>>> &v, int num, BlockQueue<int> &q) // 创建生产者线程
{
    for (int i = 0; i < num; i++)
    {
        string name = "product-" + to_string(i + 1);
        v.emplace_back(productFunc, q, name);
    }
}
void consumerFunc(BlockQueue<int> &q, string &name) // 消费线程函数——去拿数据
{
    int data;
    while (1)
    {
        q.Outqueue(&data, name);
        cout << "消费者外部>> " << name << "拿到数据了:" << data << endl;
        // sleep(1);
    }
}
void create_consumer(vector<Thread<BlockQueue<int>>> &v, int num, BlockQueue<int> &q) // 创建消费者线程
{
    for (int i = 0; i < num; i++)
    {
        string name = "consumer-" + to_string(i + 1);
        v.emplace_back(consumerFunc, q, name);
    }
}

int main()
{
    vector<Thread<BlockQueue<int>>> v;
    BlockQueue<int> q(3, gmutex, pro_cond, con_cond);

    create_product(v, 2, q);
    create_consumer(v, 2, q);

    for (auto &pthread : v)
    {
        cout << pthread.name() << " 开始了" << endl;
        pthread.start();
    }
    for (auto &pthread : v)
    {
        pthread.join();
    }

    return 0;
}